package com.css.fxfzysx.util;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ThreadPoolUtil {
    private ExecutorService executorService;

    @PostConstruct
    private void afterApplicationStart() {
        //特殊情况下可能会OOM
        executorService = Executors.newCachedThreadPool();
    }

    public ExecutorService getCachedThreadPool() {
        return executorService;
    }

    public ExecutorService getScheduleThreadPool(int threadNum){
        return Executors.newScheduledThreadPool(threadNum);
    }

    public ExecutorService getFixedThreadPool(int threadNum){
         return Executors.newFixedThreadPool(threadNum);
    }

    //根据返回条数创建n个List，至少为n个，10条以上每加10条，加1条线程
    public int countThreadNum(int n, int listSize) {
        //如果少于10个就是listSize 个线程，如果多于10，就每增加10条数据加1个线程；
        if(listSize<n){
            return listSize;
        }
        int add = Math.max((listSize - 10) / 10, 0);
        n += add;
        return n;
    }

    public List<List> cutList(int n, List content) {
        List<List> pageDataLists = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            List list = new ArrayList();
            pageDataLists.add(list);
        }
        //将分页数据分割为n个List,放入pageDataLists
        for (int i = 0; i < content.size(); i++) {
            pageDataLists.get((i + 1) % n).add(content.get(i));
        }
        return pageDataLists;
    }
}
